package com.geeke.org.service;

import java.util.List;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import com.geeke.common.service.TreeService;
import com.geeke.common.data.PageRequest;
import com.geeke.common.data.Parameter;
import com.geeke.config.exception.CommonJsonException;
import com.geeke.org.dao.CompanyDao;
import com.geeke.org.entity.Company;
import com.geeke.utils.ResultUtil;
import com.geeke.utils.constants.ErrorEnum;
import com.google.common.collect.Lists;
/**
 * 公司 Service
 * @author
 * @version
 */

@Service("companyService")
@Transactional(readOnly = true)
public class CompanyService extends TreeService<CompanyDao, Company> {

    @Transactional(readOnly = false)
    @Override
    public Company save(Company company) {
        // 约束条件处理
        List<Parameter> params = Lists.newArrayList();
        // 编号重复验证
        params.clear();
        // 根据需求或者数据库表字段是否唯一需要重复性检查字段
        params.add(new Parameter("company.code", "=", company.getCode()));

        if(!StringUtils.isBlank(company.getId())) {
          params.add(new Parameter("company.id", "<>", company.getId()));
        }
        // 表有del_flag字段，则使用delFlag
        params.add(new Parameter("company.del_flag", "=", company.getDelFlag()));

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同编号"));
        }
        
        // 名称重复验证
        params.clear();
        params.add(new Parameter("company.name", "=", company.getName()));

        if(!StringUtils.isBlank(company.getId())) {
          params.add(new Parameter("company.id", "<>", company.getId()));
        }
        params.add(new Parameter("company.del_flag", "=", company.getDelFlag()));

        if(this.dao.count(new PageRequest(params)) > 0) {
            throw new CommonJsonException(ResultUtil.warningJson(ErrorEnum.E_50001, "已存在相同名称"));
        }

        return super.save(company);
    }

    // 根据需求实现的其他方法
} 